package code.hkgolden.android.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class XmlPullChannelParser extends BaseChannelParser {
	@Override
	public Map<String, String> channels(InputStream inputStream) {
		XmlPullParser parser = Xml.newPullParser();
		LinkedHashMap<String, String> channelMap = null;
		try {
			parser.setInput(inputStream, null);
			int eventType = parser.getEventType();
			boolean done = false;
			while (eventType != XmlPullParser.END_DOCUMENT && !done) {
				String name = null;
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					name = parser.getName();
					if (name.equals(SELECT)) {
						channelMap = new LinkedHashMap<String, String>();
					} else if (channelMap != null) {
						if (name.equalsIgnoreCase(OPTION)) {
							final String key = parser.getAttributeValue("",
									"value");
							final String value = parser.nextText();
							channelMap.put(key, value);
						}
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return channelMap;
	}
}
